const router = require('koa-router')()
const multer = require('koa-multer');
const path = require('path');
const sqlQuery = require('../db.js');
const svgCaptcha = require('svg-captcha');

router.prefix('/users')

let storage = multer.diskStorage({
  destination: path.resolve('public/images'),
  filename: (ctx, file, cb)=>{
    let suffix = file.originalname.split('.')[1];
      cb(null, Date.now()+"."+suffix);
  }
});
let fileFilter = (ctx, file ,cb)=>{
let suffix = file.originalname.split('.')[1];
  if (!suffix in ['jpg','png','jpeg','gif']){
      cb(null, false); 
  }else {
      cb(null, true); 
  }
}
let upload = multer({ storage: storage, fileFilter: fileFilter });

/*
router.post('/addcarimg',upload.single('pic'), async ctx => {
  let { carName, carTime } = ctx.req.body
  let file = ctx.req.file;
  ctx.body = {
    status: 0,
    message: {
      carName: carName,
      carTime: carTime,
      file:file,
      fileName:file.filename
    }
  }
})
*/
//验证码生成器
router.get('/verifyCode', async (ctx, next) => {
  try {
    const codeConfig = {
      size: 4, // 验证码长度
      ignoreChars: '0oO1ilI', // 验证码字符中排除 0oO1ilI
      noise: 2, // 干扰线条的数量
      width: 160,
      height: 50,
      fontSize: 50,
      color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
      background: '#eee',
    };
    const captcha = svgCaptcha.create(codeConfig);
    let verifCode = captcha.text.toLowerCase();
    let rand = await sqlQuery(`select floor(1+rand()*(select count(*) from verif)) as rand`, []);
    let sql = `select v_url from verif where v_id=? and v_status=1`;
    let result = await sqlQuery(sql, [rand[0].rand]);
    let verif = {
      verifCode,
      verifImage: result[0].v_url
    }
    ctx.body = {
      status: 1,
      message: verif
    }
  } catch (error) {
    next(error);
  }
});

//登录验证
router.post('/userlogin', async (ctx, next) => {
  let sql = `select * from users where u_phone=? 
              or u_email=?
              or u_account=?
              and u_password=? and u_status=1`;
  try {
    let { user, password, login } = ctx.request.body;
    let result = await sqlQuery(sql, [user, user, user, password]);
    if (result.length === 0) {
      ctx.body = {
        status: 0,
        message:"账号不存在"
      }
      return;
    }
    if (result[0].u_status === 0) {
      ctx.body = {
        status: 0,
        message:"账号异常"
      }
      return;
    }
    if (result[0].u_login === 1) {
      ctx.body = {
        status: 0,
        message:"账号已在线"
      }
      return;
    }
    await sqlQuery('update users set u_login=? where u_id=?', [login,result[0].u_id]);
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error);
  }
})
//根据id查询用户
router.get('/getUser/:id', async (ctx, next) => {
  try {
    let { id } = ctx.params;
    let result = await sqlQuery('select * from users where u_id=?', [id]);
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error);
  }
})
// 查询用户所有信息
router.get('/getUser', async (ctx, next) => {
  try {
    let result = await sqlQuery('select * from users');
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error);
  }
})

// 修改密码
router.put("/user",async (ctx, next)=>{
	try {   
    let {u_password,u_id} = ctx.request.body;
    let sql = "update users set u_password=?,u_login=0 where u_id=?";
    let result = await sqlQuery(sql,[u_password,u_id]);
      ctx.body = {
        status:1,
        message:result
      }
    
  } catch (error) {
    next(error);
  }
	
});

router.get("/exit/:id", async (ctx, next) => {
  try {
    let id = ctx.params.id;
    let result = await sqlQuery('update users set u_login=0 where u_id=?', [id]);
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error);
  }
})

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
